package cc.eddic.examinationsystem.core;


import cc.eddic.examinationsystem.dto.StudentModel;
import cc.eddic.examinationsystem.dto.ThymeleafUserDetails;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.ModelAttribute;

@Slf4j
public abstract class BaseController {

    @ModelAttribute("currentUser")
    public StudentModel currentUser() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();

        if (log.isDebugEnabled())
            log.debug("auth principal = {}, details = {}", auth.getPrincipal(), auth.getDetails());
        if (auth.getPrincipal() instanceof ThymeleafUserDetails) {
            val tud = (ThymeleafUserDetails) auth.getPrincipal();
            return StudentModel.from(tud.getUser());
        }

        log.warn("current user is not ThymeleafUserDetails");
        return StudentModel.builder().build();
    }

}
